{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4be99c06",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.colors import ListedColormap\n",
    "from matplotlib.animation import FuncAnimation\n",
    "\n",
    "# 地图大小\n",
    "MAP_SIZE = 100\n",
    "#邻域\n",
    "neighbor_group=np.arange(-1,2,1)\n",
    "# 国家数量\n",
    "NUM_COUNTRIES = 2\n",
    "\n",
    "# 初始化地图\n",
    "map = np.random.randint(1, NUM_COUNTRIES + 1, size=(MAP_SIZE, MAP_SIZE))\n",
    "\n",
    "# 定义颜色映射\n",
    "colors = ['white', 'red', 'blue', 'green', 'yellow', 'purple', 'orange']  # 最多支持7个国家\n",
    "cmap = ListedColormap(colors[:NUM_COUNTRIES + 1])\n",
    "def get_p_line(map):\n",
    "    p_line=[]\n",
    "    for n in range(NUM_COUNTRIES):\n",
    "        for i in range(MAP_SIZE):\n",
    "            area,edge=0,1\n",
    "            for j in range(MAP_SIZE):\n",
    "                if map[i][j]==n:\n",
    "                    area+=1\n",
    "                    for di in neighbor_group:\n",
    "                        for dj in neighbor_group:\n",
    "                            if di == 0 and dj == 0:\n",
    "                                continue  # 跳过自身\n",
    "                            ni, nj = i + di, j + dj\n",
    "                            if 0 <= ni < MAP_SIZE and 0 <= nj < MAP_SIZE and map[ni][nj]!=n:\n",
    "                                edge+=1\n",
    "            p_line.append(area/edge)\n",
    "    return p_line      \n",
    "# 可视化函数\n",
    "def plot_map(map, ax,step):\n",
    "    fig, ax = plt.subplots(figsize=(10, 10))\n",
    "    ax.imshow(map, cmap=cmap, vmin=0, vmax=NUM_COUNTRIES)\n",
    "    ax.set_title(\"Step:\"+str(step))\n",
    "    plt.savefig(r\"D:\\3_bodies\\live_game\\wg_\"+str(step)+\".jpg\")\n",
    "    plt.show()\n",
    "\n",
    "# 更新函数（元胞自动机规则）\n",
    "def update(map):\n",
    "    new_map = map.copy()\n",
    "    #p_line=get_p_line(map)\n",
    "    for i in range(MAP_SIZE):\n",
    "        for j in range(MAP_SIZE):\n",
    "            current_country = map[i][j]\n",
    "            neighbors = []\n",
    "            # 获取8邻域\n",
    "            \n",
    "            for di in neighbor_group:\n",
    "                for dj in neighbor_group:\n",
    "                    if di == 0 and dj == 0:\n",
    "                        continue  # 跳过自身\n",
    "                    ni, nj = i + di, j + dj\n",
    "                    if 0 <= ni < MAP_SIZE and 0 <= nj < MAP_SIZE:\n",
    "                        neighbors.append(map[ni][nj])\n",
    "            \n",
    "            # 统计邻域中每个国家的数量\n",
    "            neighbor_counts = {country: neighbors.count(country) for country in range(1, NUM_COUNTRIES + 1)}\n",
    "            # 找到邻域中最多的国家\n",
    "            max_country = max(neighbor_counts, key=neighbor_counts.get)\n",
    "            # 如果邻域中最多的国家不是当前国家，则改变当前细胞\n",
    "            if max_country != current_country and neighbor_counts[max_country] > neighbor_counts[current_country]:\n",
    "                new_map[i][j] = max_country\n",
    "    return new_map\n",
    "\n",
    "# 动态可视化\n",
    "\n",
    "\n",
    "for step in range(1000):\n",
    "    map = update(map)\n",
    "    plot_map(map, ax,step)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "151fb599",
   "metadata": {},
   "outputs": [],
   "source": [
    "#imgs2video\n",
    "import os\n",
    "import cv2\n",
    "from PIL import Image\n",
    "fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D') \n",
    "path=r\"D:\\3_bodies\\live_game\\wg_\"#input(\"path?\")\n",
    "save_path=r\"D:/3_bodies/wg_7.mp4\"#input(\"save_path?\")\n",
    "post_video=cv2.VideoWriter(save_path, fourcc, 30,(720,720))\n",
    "len_img=660\n",
    "for i in range(len_img+1):\n",
    "    print(path+str(i)+\".jpg\")\n",
    "    img=cv2.imread(path+str(i)+\".jpg\")\n",
    "    post_video.write(img)\n",
    "    if i==len_img:\n",
    "        for t in range(100):\n",
    "            post_video.write(img)\n",
    "    del img\n",
    "    #if filename==\"0.jpg\":\n",
    "        #Image.fromarray(img).show()\n",
    "\n",
    "post_video.release()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "471a77d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#考虑国力=国土/边境\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.colors import ListedColormap\n",
    "from matplotlib.animation import FuncAnimation\n",
    "\n",
    "# 地图大小\n",
    "MAP_SIZE = 100\n",
    "#邻域\n",
    "neighbor_group=np.arange(-2,3,1)\n",
    "# 国家数量\n",
    "NUM_COUNTRIES = 7\n",
    "\n",
    "# 初始化地图\n",
    "map = np.random.randint(1, NUM_COUNTRIES + 1, size=(MAP_SIZE, MAP_SIZE))\n",
    "\n",
    "# 定义颜色映射\n",
    "colors = ['white', 'red', 'blue', 'green', 'yellow', 'purple', 'orange']  # 最多支持7个国家\n",
    "cmap = ListedColormap(colors[:NUM_COUNTRIES + 1])\n",
    "def get_p_line(map):\n",
    "    p_line=[]\n",
    "    for n in range(NUM_COUNTRIES):\n",
    "        area,edge=0,1\n",
    "        for i in range(MAP_SIZE):\n",
    "            for j in range(MAP_SIZE):\n",
    "                if map[i][j]==n+1:\n",
    "                    area+=1\n",
    "                    for di in neighbor_group:\n",
    "                        for dj in neighbor_group:\n",
    "                            if di == 0 and dj == 0:\n",
    "                                continue  # 跳过自身\n",
    "                            ni, nj = i + di, j + dj\n",
    "                            if 0 <= ni < MAP_SIZE and 0 <= nj < MAP_SIZE and map[ni][nj]!=n+1:\n",
    "                                edge+=1\n",
    "        p_line.append(area**0.5/(100*edge+100*(edge*area+1)**0.5))\n",
    "    print(p_line)\n",
    "    return p_line      \n",
    "# 可视化函数\n",
    "def plot_map(map, ax,step):\n",
    "    fig, ax = plt.subplots(figsize=(10, 10))\n",
    "    ax.imshow(map, cmap=cmap, vmin=0, vmax=NUM_COUNTRIES)\n",
    "    ax.set_title(\"Step:\"+str(step))\n",
    "    plt.savefig(r\"D:\\3_bodies\\live_game\\wg_\"+str(step)+\".jpg\")\n",
    "    plt.show()\n",
    "\n",
    "# 更新函数（元胞自动机规则）\n",
    "def update(map):\n",
    "    new_map = map.copy()\n",
    "    p_line=get_p_line(map)\n",
    "    for i in range(MAP_SIZE):\n",
    "        for j in range(MAP_SIZE):\n",
    "            current_country = map[i][j]\n",
    "            neighbors = []\n",
    "            # 获取8邻域\n",
    "            \n",
    "            for di in neighbor_group:\n",
    "                for dj in neighbor_group:\n",
    "                    if di == 0 and dj == 0:\n",
    "                        continue  # 跳过自身\n",
    "                    ni, nj = i + di, j + dj\n",
    "                    if 0 <= ni < MAP_SIZE and 0 <= nj < MAP_SIZE:\n",
    "                        neighbors.append(map[ni][nj])\n",
    "            \n",
    "            # 统计邻域中每个国家的数量\n",
    "            neighbor_counts = {country: neighbors.count(country) for country in range(1, NUM_COUNTRIES + 1)}\n",
    "            for n in range(NUM_COUNTRIES):\n",
    "                neighbor_counts[n+1]=neighbor_counts[n+1]*p_line[n]\n",
    "            # 找到邻域中最多的国家\n",
    "            max_country = max(neighbor_counts, key=neighbor_counts.get)\n",
    "            # 如果邻域中最多的国家不是当前国家，则改变当前细胞\n",
    "            if max_country != current_country and neighbor_counts[max_country] > neighbor_counts[current_country]:\n",
    "                new_map[i][j] = max_country\n",
    "    return new_map\n",
    "\n",
    "# 动态可视化\n",
    "\n",
    "\n",
    "for step in range(1000):\n",
    "    map = update(map)\n",
    "    plot_map(map, ax,step)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "347b99e2",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
